<?php
namespace Realisation\Bash;

use Model\Parser\ParserOneInterface;
use Model\Parser\ParserException;
use Symfony\Component\DomCrawler\Crawler;
use Model\Entity\Message;

/**
 * Description of OneParser
 *
 * @author pahhan
 */
class OneParser implements ParserOneInterface
{
    public function getMessage(Crawler $crawler)
    {
        $content_el = $crawler->filter('div.text');
        if( !$content_el->count() ) {
            throw new ParserException('Cant find content by "div.text"');
        }
        $content = $content_el->html();

        $message = new Message();

        $id_el = $crawler->filter('a.id');
        if( !$id_el->count() ) {
            throw new ParserException('Cant find content by "a.id"');
        }

        $url = $id_el->link()->getUri();
        $message->setExternalId(preg_replace('/[^\\d]/', '', $url, -1));
        $message->setContent($content);

        $date_el = $crawler->filter('span.date');
        $published_at = NULL;
        if( $date_el->count() ) {
            $published_at = new \DateTime($date_el->text());
        }
        $message->setPublishedAt($published_at);


        return $message;
    }

    protected function processDate($date)
    {
        $matches = NULL;
        $result = preg_match('/(\\d{1,2}) ([А-Яа-яЁё]+) (\\d{4}).*(\\d\\d):(\\d\\d)/u', $date, $matches);

        if( !($result && count($matches) === 6) ) return NULL;
        $month = \Util\Helper::ruMonthToNumber($matches[2]);

        $dt = new \DateTime();
        $dt->setDate($matches[3], $month, $matches[1]);
        $dt->setTime($matches[4], $matches[5], 0);

        return $dt;
    }


}

